// 版权归 瞄你个汪 所有。使用本代码应遵守相关法律法规和Apache 2.0开源许可要求。
package top.geeke.toolkit;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.crypto.SecureUtil;
import org.apache.logging.log4j.util.Strings;
import top.geeke.config.AppConfiguration;
import top.geeke.entity.SysUser;
import top.geeke.eunm.SysGenderEnum;

/**
 * <p>
 * 系统用户工具类
 * </p>
 *
 * @author 瞄你个汪
 * @since 2024/5/29 12:24
 */
public class SysUserTool {
    private static final AppConfiguration appConfig;

    static {
        appConfig = SpringBeanManager.getBean(AppConfiguration.class);
    }

    /**
     * 密码加密
     * @param password 密码
     * @param ignoreStrengthValidation 忽略强密码验证
     */
    public static String cryptoPassword(String password, boolean ignoreStrengthValidation) {
        AppConfiguration.CryptogramOption cryptogram = appConfig.getCryptogram();

        // 强密码验证
        if (!ignoreStrengthValidation && cryptogram.getStrongPassword() && !password.matches(cryptogram.getPasswordStrengthValidation())) {
            throw new RuntimeException(cryptogram.getPasswordStrengthValidationMsg());
        }

        String cryptoType = cryptogram.getCryptoType();
        if ("SM2".equalsIgnoreCase(cryptoType)) {
            return EncryptTool.encryptHex(password);
        } else if ("MD5".equalsIgnoreCase(cryptoType)) {
            return SecureUtil.md5(password);
        } else {
            throw new RuntimeException("不支持的加密方式：" + cryptoType);
        }
    }

    /**
     * 验证密码
     * @param inputPassword 输入的密码
     * @param ciphertextPassword 旧密码密文
     * @return 验证通过返回true
     */
    public static boolean validationPassword(String inputPassword, String ciphertextPassword) {
        return ciphertextPassword.equals(cryptoPassword(inputPassword, true));
    }

    /**
     * 验证加密的密码
     * @param inputPassword 输入的密码
     * @param ciphertextPassword 旧密码密文
     * @return 验证通过返回true
     */
    public static boolean validationCipherPassword(String inputPassword, String ciphertextPassword) {
        return ciphertextPassword.equals(cryptoPassword(EncryptTool.decryptStr(inputPassword), true));
    }

    /**
     * 根据证件号设置关联信息
     * @param user 用户对象
     * @param idNum 证件号
     */
    public static void setRelatedInfoByIdCardNumber(SysUser user, String idNum) {
        IdcardUtil.Idcard idcard = new IdcardUtil.Idcard(idNum);

        int age = idcard.getAge();
        Integer gender = idcard.getGender();
        String province = idcard.getProvince();
        DateTime birthDate = idcard.getBirthDate();

        user.setAge(age);
        user.setIdCardNum(idNum);
        user.setBirthday(birthDate.toSqlDate().toLocalDate());
        user.setSex(gender == 0 ? SysGenderEnum.Female : SysGenderEnum.Male);

        if (Strings.isEmpty(user.getOrigin())) {
            user.setOrigin(province);
        }
    }
}
